<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <title>副屏</title>
    <link rel="stylesheet" href="./css/index.css" />
    <!-- 引入 Swiper CSS -->
    <link rel="stylesheet" href="./css/swiper-bundle.min.css" />
    <script src="./js/vue3.js"></script>
    <script src="./js/flexible.js"></script>
  </head>
  <body>
    <div id="app">
      <div class="page-body">
        <div class="body-left">
          <div class="goods">
            <!-- <div>{{settingConfig.secondScreen}} {{goods.length}} {{swiperConfig.imgUrls}}</div> -->
            <div class="goods-title">
              <div>数量</div>
              <div>原价(元)</div>
              <div>售价(元)</div>
              <div>金额(元)</div>
            </div>
            <div class="goods-list">
              <div class="good" v-for="(item, index) in goods" :key="index">
                <div class="cu-box">
                  <div v-if="item.promotionType > 0" class="cu">促</div>
                </div>
                <div class="good-content flex-1 w-0">
                  <div class="font-size-14">
                    <span>{{item.productName}}</span>
                    <template v-if="item.productType == 10">
                      <span v-if="item.unitName">/{{ item.unitName }}</span>
                    </template>

                    <template v-else-if="item.productType == 20">
                      <span v-if="item.specField">{{ item.specField }} </span>
                      <span v-if="item.unitName">/{{ item.unitName }}</span>
                      <span v-if="item.packSize">({{ item.packSize }})</span>
                    </template>

                    <template v-else-if="item.productType == 30">
                      <span v-if="item.specField">/{{ item.specField }} </span>
                      <span v-if="item.specField1">/{{ item.specField1 }}</span>
                      <span v-if="item.unitName">/{{ item.unitName }}</span>
                    </template>

                    <template v-else-if="item.productType == 40">
                      <span v-if="item.unitName">/{{ item.unitName }}</span>
                    </template>
                  </div>
                  <div class="price-content flex align-center justify-between">
                    <div>x{{item.num}}</div>
                    <div
                      :class="['text-line color-2', !item.promotionPrice && 'opacity-0']"
                    >
                      {{item.retailPrice.wtoFixed(2)}}
                      <template v-if=""> </template>
                    </div>
                    <div>
                      {{(item.promotionPrice || item.retailPrice).wtoFixed(2)}}
                    </div>
                    <div>
                      {{(FloatMul(item.num,item.promotionPrice ||
                      item.retailPrice)).wtoFixed(2)}}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div
              class="goods-total flex align-center justify-between"
              style="background-color: #fff"
            >
              <div>合计</div>
              <div>
                <span>优惠</span>
                <span class="color-price font-weight-700">￥4.03</span>

                <span class="m-l-20">应付</span>
                <span class="color-price font-weight-700"
                  >￥<span class="font-size-24">{{totalPrice}}</span></span
                >
              </div>
            </div>
          </div>
        </div>
        <div class="body-right">
          <!-- Swiper 容器 -->
          <div class="swiper" v-if="swiperConfig.imgUrls.length">
            <div class="swiper-wrapper">
              <!-- 轮播项 -->
              <div
                class="swiper-slide"
                v-for="(image, index) in swiperConfig.imgUrls"
                :key="index"
              >
                <img class="item-img" :src="image" :alt="image" />
              </div>
            </div>
            <!-- 如果需要分页器 -->
            <!-- <div class="swiper-pagination"></div> -->

            <!-- 如果需要导航按钮 -->
            <!-- <div class="swiper-button-prev"></div>
            <div class="swiper-button-next"></div> -->

            <!-- 如果需要滚动条 -->
            <!-- <div class="swiper-scrollbar"></div> -->
          </div>
        </div>
      </div>

      <!-- v-if="!goods.length && swiperConfig.imgUrls.length && settingConfig.secondScreen != 1" -->
      <div
        v-if="(settingConfig.secondScreen == 1 || !goods.length) && swiperConfig.imgUrls.length "
        class="fix-swiper"
      >
        <div class="swiper" v-if="swiperConfig.imgUrls.length">
          <div class="swiper-wrapper">
            <div
              class="swiper-slide"
              v-for="(image, index) in swiperConfig.imgUrls"
              :key="index"
            >
              <img class="item-img" :src="image" :alt="image" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
  <!-- 引入 Swiper JS -->
  <script src="./js/swiper-bundle.min.js"></script>
  <script type="text/javascript">
    const { createApp, onMounted } = Vue;
    const app = createApp({
      data() {
        return {
          // 副屏设置
          settingConfig: {
            // 这里可以添加一些配置项
            secondScreen: 1, //1广告模式，2商品模式
          },
          goods: [],
          swiperConfig: {
            carouselTime: "",
            imgUrls: [],
          },
          swiperInstance: null,
          fixSwiperInstance: null,
        };
      },
      computed: {
        totalPrice() {
          if (this.goods.length) {
            return this.goods
              .reduce((total, item) => {
                return this.FloatAdd(
                  total,
                  this.FloatMul(
                    item.num,
                    item.promotionPrice || item.retailPrice
                  )
                );
              }, 0)
              .wtoFixed(2);
          }
          return 0;
        },
      },
      mounted() {
        this.initSwiper();
        console.log("副屏mounted");
      },
      methods: {
        initSwiper() {
          this.$nextTick(() => {
            this.fixSwiperInstance = new Swiper(".fix-swiper .swiper", {
              // 可选参数
              direction: "horizontal", // 垂直切换可选 'vertical'
              loop: true, // 循环模式
              autoplay: {
                delay: 3000, // 3秒切换一次
                disableOnInteraction: true, // 用户操作后继续自动播放
              },
            });
          });
        },
        onSendData(data, type = "setting") {
          console.log("副屏收到主屏消息", data, type);
          // this.settingConfig = data;
          switch (type) {
            case "setting":
              this.settingConfig = data || {};
              break;
            case "goods":
              this.goods = data || [];
              break;
            default:
              // 此举为了销毁代码，重新生成swiper实例
              this.settingConfig = { carouselTime: 5, imgUrls: [] };
              this.$nextTick(() => {
                let imgUrls = data.imgUrls.split(",");

                this.swiperConfig = {
                  carouselTime: data.carouselTime,
                  imgUrls: imgUrls,
                };

                this.$nextTick(() => {
                  this.swiperInstance = new Swiper(".swiper", {
                    // 可选参数
                    direction: "horizontal", // 垂直切换可选 'vertical'
                    loop: true, // 循环模式
                    autoplay: {
                      delay: data.carouselTime * 1000, // 3秒切换一次
                      disableOnInteraction: true, // 用户操作后继续自动播放
                    },
                  });
                });
                // this.swiperInstance.update();
                // this.swiperInstance.autoplay.start();
              });
              break;
          }
          // // 发送消息给主屏
          // if (window.lyjsdk) {
          //   window.lyjsdk.sendToFirstScreen(this.settingConfig);
          // }
        },

        IsEmpty(obj) {
          if (
            obj == null ||
            obj == "undefined" ||
            obj === "" ||
            obj == undefined
          ) {
            return true;
          } else {
            return false;
          }
        },

        //加
        FloatAdd(arg1, arg2) {
          if (this.IsEmpty(arg1)) arg1 = 0;
          if (this.IsEmpty(arg2)) arg2 = 0;

          let r1, r2;
          try {
            r1 = arg1.toString().split(".")[1].length;
          } catch (e) {
            r1 = 0;
          }
          try {
            r2 = arg2.toString().split(".")[1].length;
          } catch (e) {
            r2 = 0;
          }
          const c = Math.abs(r1 - r2);
          const m = Math.pow(10, Math.max(r1, r2));
          if (c > 0) {
            const cm = Math.pow(10, c);
            if (r1 > r2) {
              arg1 = Number(arg1.toString().replace(".", ""));
              arg2 = Number(arg2.toString().replace(".", "")) * cm;
            } else {
              arg1 = Number(arg1.toString().replace(".", "")) * cm;
              arg2 = Number(arg2.toString().replace(".", ""));
            }
          } else {
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", ""));
          }
          return (arg1 + arg2) / m;
        },

        //减
        FloatSub(arg1, arg2) {
          if (this.IsEmpty(arg1)) arg1 = 0;
          if (this.IsEmpty(arg2)) arg2 = 0;

          let r1, r2;
          try {
            r1 = arg1.toString().split(".")[1].length;
          } catch (e) {
            r1 = 0;
          }
          try {
            r2 = arg2.toString().split(".")[1].length;
          } catch (e) {
            r2 = 0;
          }
          const m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
          const n = r1 >= r2 ? r1 : r2;
          return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
        },

        //乘
        FloatMul(arg1, arg2) {
          if (this.IsEmpty(arg1)) arg1 = 0;
          if (this.IsEmpty(arg2)) arg2 = 0;

          let m = 0;
          const s1 = arg1.toString();
          const s2 = arg2.toString();
          try {
            m += s1.split(".")[1].length;
          } catch (e) {}
          try {
            m += s2.split(".")[1].length;
          } catch (e) {}
          return (
            (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
            Math.pow(10, m)
          );
        },

        //除
        FloatDiv(arg1, arg2) {
          if (this.IsEmpty(arg1)) arg1 = 0;
          if (this.IsEmpty(arg2)) arg2 = 0;

          let t1 = 0,
            t2 = 0;
          try {
            t1 = arg1.toString().split(".")[1].length;
          } catch (e) {}
          try {
            t2 = arg2.toString().split(".")[1].length;
          } catch (e) {}

          const r1 = Number(arg1.toString().replace(".", ""));
          const r2 = Number(arg2.toString().replace(".", ""));
          // 0/0 = NaN
          return (r1 / r2 || 0) * Math.pow(10, t2 - t1);
        },
      },
    });

    app.mount("#app");

    // 副屏接收主屏消息示例
    window.receiveData = function (result) {
      console.log("副屏收到主屏消息", result);
      let { data, type } = JSON.parse(result);
      const vm = app._instance.proxy;
      vm.onSendData(data, type);
    };

    Number.prototype.wtoFixed = function (d) {
      let s = `${this}`;
      /* eslint-disable-next-line */
      if (!d) d = 0;
      if (s.indexOf(".") === -1) s += ".";
      s += new Array(d + 1).join("0");
      if (new RegExp(`^(-|\\+)?(\\d+(\\.\\d{0,${d + 1}})?)\\d*$`).test(s)) {
        s = `0${RegExp.$2}`;
        const pm = RegExp.$1;
        let a = RegExp.$3.length;
        let b = true;
        if (a === d + 2) {
          a = s.match(/\d/g);
          if (parseInt(a[a.length - 1], 10) > 4) {
            for (let i = a.length - 2; i >= 0; i--) {
              a[i] = parseInt(a[i], 10) + 1;
              if (a[i] === 10) {
                a[i] = 0;
                b = i !== 1;
              } else break;
            }
          }
          s = a.join("").replace(new RegExp(`(\\d+)(\\d{${d}})\\d$`), "$1.$2");
        }
        if (b) s = s.substr(1);
        return (pm + s).replace(/\.$/, "");
      }
      return `${this}`;
    };
  </script>

  <style>
    /* 添加一些基本样式确保Swiper正常显示 */
    .swiper {
      width: 100%;
      height: 100%;
    }

    .swiper-slide {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .swiper-slide img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: contain;
    }

    /* 你可以根据需要调整这些样式 */
    .body-right {
      height: 100%; /* 确保父容器有明确高度 */
      overflow: hidden; /* 防止内容溢出 */
    }
  </style>
</html>
